package com.xqls.controller;

import com.alibaba.fastjson.JSONObject;
import com.xqls.bean.ExportBean;
import com.xqls.util.ExcelUtil;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@Controller
@RequestMapping("/export")
public class ExcelController {
    private static Logger logger = Logger.getLogger(ExcelController.class);
   @RequestMapping("/excel")
   @ResponseBody
  public ResponseEntity<byte[]> commonExport(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "params")String formParam){
       try {
           ExportBean exportBean=        JSONObject.parseObject(formParam,ExportBean.class);
           ByteArrayOutputStream os = new ByteArrayOutputStream();
           ExcelUtil.createWorkBook(exportBean).write(os);
           byte[] content = os.toByteArray();
           ResponseEntity<byte[]> responseEntitys=null;
               HttpHeaders headers = new HttpHeaders();
               headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
               String filename = exportBean.getSheetName()+".xls";
               //解决文件中文乱码
               String agent = request.getHeader("User-Agent").toLowerCase();
               //识别IE浏览器
               if (agent != null && (agent.indexOf("msie") != -1 ||
                       (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))) {
                   filename = URLEncoder.encode(filename, "UTF-8");
               }//IE浏览器
               else {
                   filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");}//firefox浏览器

               headers.setContentDispositionFormData("attachment",filename);  //解决文件名中文乱码问题
               responseEntitys=new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);

           return responseEntitys;
       } catch ( Exception e) {
           logger.error("导出excel异常",e);
           response.setContentType("text/html; charset=utf-8");
           PrintWriter writer = null;
           try {
               writer = response.getWriter();
           } catch (IOException e1) {
               logger.error("导出excelIOException异常",e);
           }
           writer.write("<script>alert('导出excel异常');</script>");
           writer.write("<script>window.close();</script>");
           writer.close();
           writer.flush();
           return  null;
       }



  }
}
